﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Definitions;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Common.Services;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Profiles.Controls
{
    public partial class ProfileControl : UserControl
    {
        protected HtmlGenericControl MessageBox;
        protected Label MessageLabel;

        protected Image titleImage;
        protected Label titleLabel;
        protected Label headerUserNameLabel;
        protected Button editButton;
        protected Button lockButton;
        protected Label profileLastChanged;

        protected HtmlGenericControl youTitle;
        protected HtmlGenericControl companiesTitle;
        protected HtmlGenericControl blogsTitle;
        protected HtmlGenericControl AnnouncementTitle;
        protected PlaceHolder AddButtons;

        protected Label firstNameLabel;
        protected Label lastNameLabel;
        protected HyperLink emailAddressLink;
        protected Label interestsLabel;
        protected MultiView AnnouncementView;

        protected Label aboutMeLabel;
        protected HyperLink blogLink;
        protected Label addressLabel;
        protected Label phoneLabel;

        protected Label schoolLabel;
        protected Label fieldOfStudyLabel;

        protected Label companyLabel;
        protected Label jobTitleLabel;


        protected HtmlContainerControl firstNameContainer;
        protected HtmlContainerControl lastNameContainer;
        protected HtmlContainerControl emailContainer;
        protected HtmlContainerControl interestsContainer;

        protected HtmlContainerControl contactsContainer;
        protected HtmlContainerControl aboutMeContainer;
        protected HtmlContainerControl blogContainer;
        protected HtmlContainerControl addressContainer;
        protected HtmlContainerControl phoneContainer;

        protected HtmlContainerControl educationContainer;
        protected HtmlContainerControl schoolContainer;
        protected HtmlContainerControl fieldOfStudyContainer;

        protected HtmlContainerControl jobContainer;
        protected HtmlContainerControl companyContainer;
        protected HtmlContainerControl jobTitleContainer;

        protected Repeater companiesRepeater;
        protected Repeater blogsRepeater;
        protected Repeater AnnouncementRepeater;
        protected Repeater AnnouncementUserRepeater;
        protected ProfileEventsControl UserEventsList;

        private string _profileOwnerName;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            companiesRepeater.ItemDataBound += CompaniesRepeaterItemDataBound;
            blogsRepeater.ItemDataBound += BlogsRepeaterItemDataBound;
            AnnouncementRepeater.ItemDataBound += AnnouncementRepeaterItemDataBound;
            AnnouncementUserRepeater.ItemDataBound += AnnouncementUserRepeaterItemDataBound;
            editButton.Click += EditButtonClick;

            // TODO: Tee control korda
            if (lockButton == null)
                lockButton = new Button();
            lockButton.Click += LockButtonClick;
        }

        void LockButtonClick(object sender, EventArgs e)
        {
            var rep = new UserProfileRepository(SPContext.Current.Web);
            rep.LockProfile(Item.Id);
            Response.Redirect(Request.RawUrl);

        }

        protected void EditButtonClick(object sender, EventArgs e)
        {
            Response.Redirect(EnetaApplication.PortalProfileEditPageUrl + "?profileID=" + Item.Id, true);
        }

        protected void CompaniesRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (CompanyDto)e.Item.DataItem;

            var companyAnchor = (HtmlAnchor)e.Item.FindControl("companyAnchor");
            companyAnchor.Name = "c" + item.Id;

            var companyName = (Label)e.Item.FindControl("companyName");
            companyName.Text = item.Title;

            var companyLastChanged = (Label)e.Item.FindControl("companyLastChanged");
            companyLastChanged.Text = item.Modified.ToShortDateString();

            var companyStatus = (Label)e.Item.FindControl("companyStatus");
            var companyStatusComment = (Label)e.Item.FindControl("companyStatusComment");
            var companyUrlContainer = (HtmlGenericControl)e.Item.FindControl("companyUrlContainer");
            companyUrlContainer.Visible = false;

            switch (item.Status)
            {
                case SPModerationStatusType.Draft:
                case SPModerationStatusType.Pending:
                    companyStatus.Text = Resources.GetResourceString("Pending");
                    companyStatus.Style["color"] = "#FFCC00";
                    break;
                case SPModerationStatusType.Approved:
                    companyUrlContainer.Visible = true;
                    companyStatus.Text = Resources.GetResourceString("Approved");
                    companyStatus.Style["color"] = "green";
                    break;
                case SPModerationStatusType.Denied:
                    companyStatus.Text = Resources.GetResourceString("Denied");
                    companyStatus.Style["color"] = "red";
                    break;
            }
            companyStatusComment.Visible = false;

            if (!string.IsNullOrEmpty(item.StatusComment))
            {
                companyStatusComment.Text = " (" + item.StatusComment + ") ";
                companyStatusComment.Visible = true;
            }


            if (!MyProfile && !CurrentUserIsAdmin)
            {
                companyStatus.Visible = false;
                companyStatusComment.Visible = false;
            }
            else
            {
                companyStatus.Visible = true;
                companyStatusComment.Visible = true;
            }

            if (CurrentUserIsAdmin)
                companyUrlContainer.Visible = true;

            var companyUrl = (HyperLink)e.Item.FindControl("companyUrl");
            companyUrl.NavigateUrl = item.DisplayUrl;
            companyUrl.Text = companyUrl.NavigateUrl;

            var rejectContainer = (HtmlGenericControl)e.Item.FindControl("rejectContainer");
            rejectContainer.Visible = CurrentUserIsAdmin;

            var buttonContainer = (HtmlGenericControl)e.Item.FindControl("buttonContainer");
            buttonContainer.Visible = (MyProfile || CurrentUserIsAdmin);


            var button = (Button)e.Item.FindControl("editCompanyButton");
            button.CommandArgument = item.Id.ToString();
            button.ID = "button_" + e.Item.ItemIndex;
            button.Click += EditCompanyButtonClick;
            button.Visible = buttonContainer.Visible;

            button = (Button)e.Item.FindControl("acceptCompanyButton");
            button.CommandArgument = item.Id.ToString();
            button.ID = "abutton_" + e.Item.ItemIndex;
            button.Click += AcceptCompanyButtonClick;

            try
            {
                button.Visible = CurrentUserIsAdmin &&
                                 (item.Status == SPModerationStatusType.Denied ||
                                  item.Status == SPModerationStatusType.Pending);
            }
            catch
            {
                button.Visible = false;
            }
            button = (Button)e.Item.FindControl("rejectCompanyButton");
            button.CommandArgument = item.Id.ToString();
            button.ID = "rbutton_" + e.Item.ItemIndex;
            button.Click += RejectCompanyButtonClick;

            try
            {
                button.Visible = CurrentUserIsAdmin &&
                                 (item.Status == SPModerationStatusType.Approved ||
                                  item.Status == SPModerationStatusType.Pending);
            }
            catch
            {
                button.Visible = true;
            }
        }

        protected void EditCompanyButtonClick(object sender, EventArgs e)
        {
            var button = (Button)sender;
            Response.Redirect(EnetaApplication.PortalCompanyEditPageUrl + "?companyID=" + button.CommandArgument);
            Response.End();
        }
        protected void AcceptCompanyButtonClick(object sender, EventArgs e)
        {
            var siteId = SPContext.Current.Site.ID;
            var button = (Button)sender;
            var textId = button.UniqueID.Substring(0, button.UniqueID.Length - button.ID.Length);
            textId += "rejectReasonField";
            var text = Request.Form[textId];
            var currentEditor = SPContext.Current.Web.CurrentUser.ToString();
            var id = int.Parse(((Button)sender).CommandArgument);
            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
            var company = repository.GetCompanyById(id);

            using (var site = new SPSite(EnetaApplication.PortalCompaniesSiteUrl))
            {
                using (var web = site.OpenWeb(GetWebUrl(site, EnetaApplication.PortalCompaniesSiteUrl)))
                {

                    var listName = PublishingWeb.GetPagesListName(web);
                    var list = web.Lists[listName];
                    var item = list.GetItemById(id);

                    var dto = new AdminActivityDto();
                    dto.Url = company.DisplayUrl;
                    dto.Module = "Companies";
                    dto.PreviousEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                    dto.PreviousStatus = item.ModerationInformation.Status;
                    dto.PreviousTimeStamp = (DateTime)item["Modified"];

                    if (item.ModerationInformation.Status == SPModerationStatusType.Denied ||
                        item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        var pubItem = PublishingPage.GetPublishingPage(item);
                        pubItem.CheckOut();
                        item["Editor"] = list.ParentWeb.SiteUsers[currentEditor];
                        pubItem.CheckIn(text);
                        item.File.Publish(text);
                        item.File.Approve(text);
                        item = list.GetItemById(id);

                        dto.CurrentEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                        dto.CurrentStatus = SPModerationStatusType.Approved;
                        dto.CurrentTimeStamp = (DateTime)item["Modified"];
                        ActivityLogger.LogActivity(dto);

                        try
                        {
                            var ownerValue = new SPFieldUserValue(web, item["Author"].ToString());
                            var owner = ownerValue.User;
                            var companyUrl = company.DisplayUrl;

                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("CompanyAccepted", owner.Name, item.Title, companyUrl, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }
                    }
                }
            }
            Response.Redirect(Request.RawUrl);
        }
        protected void RejectCompanyButtonClick(object sender, EventArgs e)
        {
            var siteId = SPContext.Current.Site.ID;
            var button = (Button)sender;
            var textId = button.UniqueID.Substring(0, button.UniqueID.Length - button.ID.Length);
            textId += "rejectReasonField";
            var text = Request.Form[textId];
            var id = int.Parse(((Button)sender).CommandArgument);
            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
            var company = repository.GetCompanyById(id);

            using (var site = new SPSite(siteId))
            {
                using (var web = site.OpenWeb(GetWebUrl(site, EnetaApplication.PortalCompaniesSiteUrl)))
                {

                    var listName = PublishingWeb.GetPagesListName(web);
                    var list = web.Lists[listName];
                    var item = list.GetItemById(id);

                    var dto = new AdminActivityDto();
                    dto.Url = company.DisplayUrl;
                    dto.Module = "Companies";
                    dto.PreviousEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                    dto.PreviousStatus = item.ModerationInformation.Status;
                    dto.PreviousTimeStamp = (DateTime)item["Modified"];

                    if (item.ModerationInformation.Status == SPModerationStatusType.Approved ||
                        item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        var pubItem = PublishingPage.GetPublishingPage(item);
                        pubItem.CheckOut();
                        pubItem.CheckIn(text);
                        item.File.Publish(text);
                        item.File.Deny(text);
                        item = list.GetItemById(id);

                        dto.CurrentEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                        dto.CurrentStatus = SPModerationStatusType.Denied;
                        dto.CurrentTimeStamp = (DateTime)item["Modified"];
                        ActivityLogger.LogActivity(dto);

                        var ownerValue = new SPFieldUserValue(web, item["Author"].ToString());
                        var owner = ownerValue.User;

                        try
                        {
                            var companyUrl = company.DisplayUrl;

                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("CompanyRejected", owner.Name, item.Title, companyUrl, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }

                    }
                }
            }
            Response.Redirect(Request.RawUrl);
        }

        private void AnnouncementRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (SPListItem)e.Item.DataItem;
            var annRep = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);
            var annItem = annRep.GetAnnouncementById(item.ID);
            var announcementAnchor = (HtmlAnchor)e.Item.FindControl("announcementAnchor");
            announcementAnchor.Name = "t" + item.ID;

            var announcementTitle = (HtmlAnchor)e.Item.FindControl("_announcementTitle");
            announcementTitle.InnerText = item.Title;
            //announcementTitle.HRef = "/uudised/teated/AnnouncementView.aspx?ID=" + item.ID;
            announcementTitle.HRef = annItem.DisplayUrl;

            var announcementLastChanged = (HtmlGenericControl)e.Item.FindControl("announcementDate");
            announcementLastChanged.InnerText = ((DateTime)item["Created"]).ToShortDateString();

            var announcementStatus = (Label)e.Item.FindControl("_announcementStatus");
            var announcementStatusComment = (Label)e.Item.FindControl("_announcementStatusComment");

            if (item.ModerationInformation != null)
            {
                switch (item.ModerationInformation.Status)
                {
                    case SPModerationStatusType.Draft:
                    case SPModerationStatusType.Pending:
                        announcementStatus.Text = Resources.GetResourceString("Pending");
                        announcementStatus.Style["color"] = "#FFCC00";
                        break;
                    case SPModerationStatusType.Approved:
                        announcementStatus.Text = Resources.GetResourceString("Approved");
                        announcementStatus.Style["color"] = "green";
                        break;
                    case SPModerationStatusType.Denied:
                        announcementStatus.Text = Resources.GetResourceString("Denied");
                        announcementStatus.Style["color"] = "red";
                        break;
                }
                announcementStatusComment.Visible = false;

                if (!string.IsNullOrEmpty(item.ModerationInformation.Comment))
                {
                    announcementStatusComment.Text = " (" + item.ModerationInformation.Comment + ") ";
                    announcementStatusComment.Visible = true;
                }
            }
            else
            {
                Logger.LogWarning("CompaniesRepeaterItemDataBound(): item has no moderation information");
            }



            if (!MyProfile && !CurrentUserIsAdmin)
            {
                announcementStatus.Visible = false;
                announcementStatusComment.Visible = false;
            }
            else
            {
                announcementStatus.Visible = true;
                announcementStatusComment.Visible = true;
            }

            var rejectContainer = (HtmlGenericControl)e.Item.FindControl("rejectContainer");
            rejectContainer.Visible = CurrentUserIsAdmin;

            var buttonContainer = (HtmlGenericControl)e.Item.FindControl("buttonContainer");
            buttonContainer.Visible = (MyProfile || CurrentUserIsAdmin);

            var button = (Button)e.Item.FindControl("editAnnouncementButton");
            button.CommandArgument = item.ID.ToString();
            button.ID = "button_" + e.Item.ItemIndex;
            button.Click += EditAnnouncementButtonClick;
            button.Visible = buttonContainer.Visible;

            button = (Button)e.Item.FindControl("acceptAnnouncementButton");
            button.CommandArgument = item.ID.ToString();
            button.ID = "abutton_" + e.Item.ItemIndex;
            button.Click += AcceptAnnouncementButtonClick;

            try
            {
                button.Visible = CurrentUserIsAdmin &&
                                 (item.ModerationInformation.Status == SPModerationStatusType.Denied ||
                                  item.ModerationInformation.Status == SPModerationStatusType.Pending);
            }
            catch
            {
                button.Visible = false;
            }

            button = (Button)e.Item.FindControl("rejectAnnouncementButton");
            button.CommandArgument = item.ID.ToString();
            button.ID = "rbutton_" + e.Item.ItemIndex;
            button.Click += RejectAnnouncementButtonClick;

            try
            {
                button.Visible = CurrentUserIsAdmin &&
                                 (item.ModerationInformation.Status == SPModerationStatusType.Approved ||
                                  item.ModerationInformation.Status == SPModerationStatusType.Pending);
            }
            catch
            {
                button.Visible = true;
            }
        }

        private void AnnouncementUserRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (SPListItem)e.Item.DataItem;
            var annRep = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);
            var annItem = annRep.GetAnnouncementById(item.ID);

            var announcementAnchor = (HtmlAnchor)e.Item.FindControl("userAnnouncementAnchor");
            if (announcementAnchor != null)
                announcementAnchor.Name = "t" + item.ID;

            var announcementStatus = (Label)e.Item.FindControl("_userAnnouncementStatus");
            var announcementStatusComment = (Label)e.Item.FindControl("_userAnnouncementStatusComment");

            if (item.ModerationInformation != null)
            {
                switch (item.ModerationInformation.Status)
                {
                    case SPModerationStatusType.Draft:
                    case SPModerationStatusType.Pending:
                        announcementStatus.Text = Resources.GetResourceString("Pending");
                        announcementStatus.Style["color"] = "#FFCC00";
                        break;
                    case SPModerationStatusType.Approved:
                        announcementStatus.Text = Resources.GetResourceString("Approved");
                        announcementStatus.Style["color"] = "green";
                        break;
                    case SPModerationStatusType.Denied:
                        announcementStatus.Text = Resources.GetResourceString("Denied");
                        announcementStatus.Style["color"] = "red";
                        break;
                }

                if (!string.IsNullOrEmpty(item.ModerationInformation.Comment))
                {
                    announcementStatusComment.Text = " (" + item.ModerationInformation.Comment + ") ";
                    announcementStatusComment.Visible = true;
                }
            }

            if (!MyProfile && !CurrentUserIsAdmin)
            {
                announcementStatus.Visible = false;
                announcementStatusComment.Visible = false;
            }
            else
            {
                announcementStatus.Visible = true;
                announcementStatusComment.Visible = true;
            }

            var announcementTitle = (HtmlAnchor)e.Item.FindControl("_userAnnouncementTitle");
            announcementTitle.InnerText = item.Title;
            //announcementTitle.HRef = "/uudised/teated/AnnouncementView.aspx?ID=" + item.ID;
            announcementTitle.HRef = annItem.DisplayUrl;

            var announcementLastChanged = (HtmlGenericControl)e.Item.FindControl("userAnnouncementDate");
            announcementLastChanged.InnerText = ((DateTime)item["Created"]).ToShortDateString();
        }

        private void EditAnnouncementButtonClick(object sender, EventArgs e)
        {
            var button = (Button)sender;
            Response.Redirect(EnetaApplication.PortalAnnouncementsEditPageUrl + "?aid=" + button.CommandArgument);
            Response.End();
        }

        protected void RejectAnnouncementButtonClick(object sender, EventArgs e)
        {
            var siteId = SPContext.Current.Site.ID;
            var button = (Button)sender;
            var textId = button.UniqueID.Substring(0, button.UniqueID.Length - button.ID.Length);
            textId += "rejectReasonField";
            var text = Request.Form[textId];
            var id = int.Parse(((Button)sender).CommandArgument);
            var annRep = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);
            var annItem = annRep.GetAnnouncementById(id);

            using (var site = new SPSite(siteId))
            {
                using (var web = site.OpenWeb(GetWebUrl(site, EnetaApplication.PortalAnnouncementsSiteUrl)))
                {

                    var listName = PublishingWeb.GetPagesListName(web);
                    var list = web.Lists[listName];
                    var item = list.GetItemById(id);

                    if (item.ModerationInformation.Status == SPModerationStatusType.Approved ||
                        item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        var pubItem = PublishingPage.GetPublishingPage(item);
                        pubItem.CheckOut();
                        pubItem.CheckIn(text);
                        item.File.Publish(text);
                        item.File.Deny(text);

                        var ownerValue = new SPFieldUserValue(web, item["Author"].ToString());
                        var owner = ownerValue.User;
                        var annLink = annItem.DisplayUrl;

                        try
                        {
                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("AnnouncementRejected", owner.Name, item.Title, annLink, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }
                    }
                    else if (item.ModerationInformation.Status == SPModerationStatusType.Draft)
                    {
                        var pubItem = PublishingPage.GetPublishingPage(item);
                        pubItem.CheckIn(text);
                        item.File.Publish(text);
                        item.File.Deny(text);

                        var ownerValue = new SPFieldUserValue(web, item["Author"].ToString());
                        var owner = ownerValue.User;
                        var annLink = annItem.DisplayUrl;

                        try
                        {
                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("AnnouncementRejected", owner.Name, item.Title, annLink, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }
                    }
                }
            }
            Response.Redirect(Request.RawUrl, false);
            return;
        }

        protected void AcceptAnnouncementButtonClick(object sender, EventArgs e)
        {
            var siteId = SPContext.Current.Site.ID;
            var button = (Button)sender;
            var textId = button.UniqueID.Substring(0, button.UniqueID.Length - button.ID.Length);
            textId += "rejectReasonField";
            var text = Request.Form[textId];
            var id = int.Parse(((Button)sender).CommandArgument);
            var annRep = new AnnouncementRepository(EnetaApplication.PortalAnnouncementsSiteUrl);
            var annItem = annRep.GetAnnouncementById(id);

            using (var site = new SPSite(siteId))
            {
                using (var web = site.OpenWeb(EnetaApplication.PortalAnnouncementsSiteUrl))
                {

                    var listName = PublishingWeb.GetPagesListName(web);
                    var list = web.Lists[listName];
                    var item = list.GetItemById(id);

                    var dto = new AdminActivityDto();
                    dto.Url = annItem.DisplayUrl;
                    dto.Module = "Announcements";
                    dto.PreviousEditor = item["Editor"].ToString();
                    dto.PreviousStatus = item.ModerationInformation.Status;
                    dto.PreviousTimeStamp = (DateTime)item["Modified"];

                    if (item.ModerationInformation.Status == SPModerationStatusType.Denied ||
                        item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        var pubItem = PublishingPage.GetPublishingPage(item);
                        pubItem.CheckOut();
                        pubItem.CheckIn(text);
                        item.File.Publish(text);
                        item.File.Approve(text);

                        var ownerValue = new SPFieldUserValue(web, item["Author"].ToString());
                        var owner = ownerValue.User;
                        var annLink = annItem.DisplayUrl;

                        try
                        {
                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("AnnouncementAccepted", owner.Name, item.Title, annLink, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }
                    }
                    else if (item.ModerationInformation.Status == SPModerationStatusType.Draft)
                    {
                        var pubItem = PublishingPage.GetPublishingPage(item);
                        pubItem.CheckIn(text);
                        item.File.Publish(text);
                        item.File.Approve(text);

                        var ownerValue = new SPFieldUserValue(web, item["Author"].ToString());
                        var owner = ownerValue.User;
                        var annLink = annItem.DisplayUrl;

                        try
                        {
                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("AnnouncementAccepted", owner.Name, item.Title, annLink, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }

                    }
                }
            }
            var cache = HttpContext.Current.Cache;
            cache.Remove("NewsAndBlogsList");
            cache.Remove("FrontPageNews");
            Response.Redirect(Request.RawUrl);
        }

        protected void BlogsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (BlogDto)e.Item.DataItem;

            var blogAnchor = (HtmlAnchor)e.Item.FindControl("blogAnchor");
            blogAnchor.Name = "b" + item.ID;

            var blogName = (HtmlAnchor)e.Item.FindControl("blogName");
            blogName.InnerText = item.Title;
            blogName.HRef = item.DisplayUrl;

            var blogUrl = (HyperLink)e.Item.FindControl("blogUrl");
            blogUrl.NavigateUrl = item.Url;
            blogUrl.Text = blogUrl.NavigateUrl;

            var rssUrl = (HyperLink)e.Item.FindControl("rssUrl");
            rssUrl.NavigateUrl = item.RssUrl;
            rssUrl.Text = rssUrl.NavigateUrl;

            var blogDescription = (Label)e.Item.FindControl("blogDescription");
            blogDescription.Text = item.Description;

            var firstEntryDate = (Label)e.Item.FindControl("firstEntryDate");
            firstEntryDate.Text = item.FirstEntryDate.ToString("dd.MM.yyyy");

            var blogLastChanged = (Label)e.Item.FindControl("blogLastChanged");
            blogLastChanged.Text = item.LastModified.ToShortDateString();

            var rejectContainer = (HtmlGenericControl)e.Item.FindControl("rejectContainer");
            rejectContainer.Visible = CurrentUserIsAdmin;

            var blogStatus = (Label)e.Item.FindControl("blogStatus");
            var blogStatusComment = (Label)e.Item.FindControl("blogStatusComment");
            switch (item.Status)
            {
                case SPModerationStatusType.Draft:
                case SPModerationStatusType.Pending:
                    blogStatus.Text = Resources.GetResourceString("Pending");
                    blogStatus.Style["color"] = "#FFCC00";
                    break;
                case SPModerationStatusType.Approved:
                    blogStatus.Text = Resources.GetResourceString("Approved");
                    blogStatus.Style["color"] = "green";
                    break;
                case SPModerationStatusType.Denied:
                    blogStatus.Text = Resources.GetResourceString("Denied");
                    blogStatus.Style["color"] = "red";
                    break;
            }

            blogStatusComment.Visible = false;
            if (!string.IsNullOrEmpty(item.StatusComment))
            {
                blogStatusComment.Text = " (" + item.StatusComment + ") ";
                blogStatusComment.Visible = true;
            }
            if (!MyProfile && !CurrentUserIsAdmin)
            {
                blogStatus.Visible = false;
                blogStatusComment.Visible = false;
            }
            var buttonContainer = (HtmlGenericControl)e.Item.FindControl("buttonContainer");
            buttonContainer.Visible = (MyProfile || CurrentUserIsAdmin);

            if (buttonContainer.Visible)
            {
                var button = (Button)e.Item.FindControl("editBlogButton");
                button.CommandArgument = item.ID.ToString();
                button.ID = "button_" + e.Item.ItemIndex;
                button.Click += EditBlogButtonClick;
                button.Visible = buttonContainer.Visible;

                //var rejectReasonField = (TextBox)e.Item.FindControl("rejectReasonField");

                button = (Button)e.Item.FindControl("acceptBlogButton");
                button.CommandArgument = item.ID.ToString();
                button.ID = "abutton_" + e.Item.ItemIndex;
                button.Click += AcceptBlogButtonClick;
                button.Visible = CurrentUserIsAdmin && (item.Status == SPModerationStatusType.Denied ||
                    item.Status == SPModerationStatusType.Pending);

                button = (Button)e.Item.FindControl("rejectBlogButton");
                button.CommandArgument = item.ID.ToString();
                button.ID = "rbutton_" + e.Item.ItemIndex;
                button.Click += RejectBlogButtonClick;
                button.Visible = CurrentUserIsAdmin && (item.Status == SPModerationStatusType.Approved ||
                    item.Status == SPModerationStatusType.Pending);
            }
        }

        protected void EditBlogButtonClick(object sender, EventArgs e)
        {
            var button = (Button)sender;
            Response.Redirect(EnetaApplication.PortalBlogEditPageUrl + "?blogID=" + button.CommandArgument);
            Response.End();
        }

        protected void AcceptBlogButtonClick(object sender, EventArgs e)
        {
            var siteId = SPContext.Current.Site.ID;
            var button = (Button)sender;

            var textId = button.UniqueID.Substring(0, button.UniqueID.Length - button.ID.Length);
            textId += "rejectReasonField";
            var text = Request.Form[textId];
            var id = int.Parse(((Button)sender).CommandArgument);
            var repository = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
            var blog = repository.GetBlogById(id);

            using (var site = new SPSite(EnetaApplication.PortalBlogSiteUrl))
            {
                using (var web = site.OpenWeb(GetWebUrl(site, EnetaApplication.PortalBlogSiteUrl)))
                {

                    var listName = PublishingWeb.GetPagesListName(web);
                    var list = web.Lists[listName];
                    var item = list.GetItemById(id);

                    var dto = new AdminActivityDto();
                    dto.Url = blog.DisplayUrl;
                    dto.Module = "Blogs";
                    dto.PreviousEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                    dto.PreviousStatus = item.ModerationInformation.Status;
                    dto.PreviousTimeStamp = (DateTime)item["Modified"];

                    if (item.ModerationInformation.Status == SPModerationStatusType.Denied ||
                        item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        item.ModerationInformation.Status = SPModerationStatusType.Approved;
                        item.ModerationInformation.Comment = text;
                        item.Update();
                        item = list.GetItemById(id);

                        dto.CurrentEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                        dto.CurrentStatus = SPModerationStatusType.Approved;
                        dto.CurrentTimeStamp = (DateTime)item["Modified"];
                        ActivityLogger.LogActivity(dto);

                        var ownerValue = new SPFieldUserValue(web, item["Owner"].ToString());
                        var owner = ownerValue.User;
                        var blogLink = blog.DisplayUrl;

                        try
                        {
                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("BlogAccepted", owner.Name, item.Title, blogLink, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }
                    }

                }
            }
            Response.Redirect(Request.RawUrl);
        }
        protected void RejectBlogButtonClick(object sender, EventArgs e)
        {
            var siteId = SPContext.Current.Site.ID;
            var button = (Button)sender;
            var textId = button.UniqueID.Substring(0, button.UniqueID.Length - button.ID.Length);
            textId += "rejectReasonField";
            var text = Request.Form[textId];
            var id = int.Parse(((Button)sender).CommandArgument);
            var repository = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
            var blog = repository.GetBlogById(id);

            using (var site = new SPSite(EnetaApplication.PortalBlogSiteUrl))
            {
                var webUrl = GetWebUrl(site, EnetaApplication.PortalBlogSiteUrl);
                using (var web = site.OpenWeb(webUrl))
                {
                    var listName = PublishingWeb.GetPagesListName(web);
                    var list = web.Lists[listName];
                    var item = list.GetItemById(id);

                    var dto = new AdminActivityDto();
                    dto.Url = blog.DisplayUrl;
                    dto.Module = "Blogs";
                    dto.PreviousEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                    dto.PreviousStatus = item.ModerationInformation.Status;
                    dto.PreviousTimeStamp = (DateTime)item["Modified"];

                    if (item.ModerationInformation.Status == SPModerationStatusType.Approved ||
                        item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        item.ModerationInformation.Status = SPModerationStatusType.Denied;
                        item.ModerationInformation.Comment = text;
                        item.Update();
                        item = list.GetItemById(id);

                        dto.CurrentEditor = new SPFieldUserValue(web, item["Editor"].ToString()).User.LoginName;
                        dto.CurrentStatus = SPModerationStatusType.Denied;
                        dto.CurrentTimeStamp = (DateTime)item["Modified"];
                        ActivityLogger.LogActivity(dto);

                        var ownerValue = new SPFieldUserValue(web, item["Owner"].ToString());
                        var owner = ownerValue.User;
                        var blogLink = blog.DisplayUrl;

                        try
                        {
                            var mailer = new MailerService();
                            var addresses = new[] { owner.Email, EnetaApplication.PortalModeratorEmail };
                            mailer.SendMailByTemplate("BlogRejected", owner.Name, item.Title, blogLink, addresses);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException(ex);
                        }

                    }
                }
            }
            Response.Redirect(Request.RawUrl);
        }

        private SPListItem _item;
        private UserProfileDto _profile;
        private UserProfileDto Item
        {
            get
            {
                if (_profile == null)
                    _profile = GetCurrentProfile();

                return _profile;
            }
        }

        public static UserProfileDto GetCurrentProfile()
        {
            var rep = new UserProfileRepository(SPContext.Current.Web);
            var request = HttpContext.Current.Request;

            var idString = request.QueryString["profileID"];

            if (!string.IsNullOrEmpty(idString))
            {
                int id;
                if (!int.TryParse(idString, out id))
                    return null;

                return rep.GetUserProfileById(id);
            }

            var name = request.QueryString["name"];
            if (!string.IsNullOrEmpty(name))
            {
                return rep.GetUserProfileByProfileName(name);
            }
            return null;
        }

        private SPListItem Item2
        {
            get
            {
                if (_item != null)
                    return _item;

                var idString = Request.QueryString["profileID"];
                if (string.IsNullOrEmpty(idString))
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["name"]))
                    {
                        _item = GetProfileByUserName();
                        return _item;
                    }
                    return null;
                }

                int id;
                if (!int.TryParse(idString, out id))
                    return null;

                try
                {
                    _item = SPContext.Current.Site.RootWeb.GetList(Lists.ProfileList).GetItemById(id);
                }
                catch
                {
                    _item = null;
                }
                return _item;
            }
        }

        private SPListItem GetProfileByUserName()
        {
            var userName = Request.QueryString["name"];
            if (string.IsNullOrEmpty(userName))
                return null;

            var rep = new UserProfileRepository(SPContext.Current.Web);
            var user = rep.GetUserProfileByProfileName(userName);
            if (user == null)
                return null;

            var siteId = SPContext.Current.Site.ID;
            using (var site = new SPSite(siteId))
            using (var web = site.OpenWeb())
            {
                var list = web.GetList(Lists.ProfileList);
                return list.GetItemById(user.Id);
            }
        }

        private Guid GetFieldId(SPListItem item, string internalName)
        {
            try
            {
                return item.Fields.GetFieldByInternalName(internalName).Id;
            }
            catch (Exception ex)
            {
                Logger.LogWarning("GetFieldId(): Field not found " + internalName);
                Logger.LogException(ex);
                throw;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            EnsureChildControls();

            lockButton.Visible = CurrentUserIsAdmin;

            MessageBox.Visible = false;
            MessageLabel.Text = string.Empty;

            if (Item == null)
            {
                if (!CurrentUserIsAdmin)
                {
                    Response.Redirect("/");
                }
                return;
            }

            if (Item.Locked)
            {
                Response.Redirect("/Lehed/ErrorNoProfile.aspx");
                Response.End();
            }



            if (MyProfile)
            {
                companiesTitle.InnerText = Resources.GetResourceString("MyCompanies");
                blogsTitle.InnerText = Resources.GetResourceString("MyBlogs");
                AnnouncementTitle.InnerText = Resources.GetResourceString("MyAnnouncements");
                youTitle.InnerText = Resources.GetResourceString("You");
                editButton.Visible = true;
                //promoBox.Visible = true;
                if (CurrentUserIsAdmin)
                {
                    //AnnouncementView.ActiveViewIndex = 0;
                    AnnouncementView.ActiveViewIndex = 1;
                }
                else
                {
                    AnnouncementView.ActiveViewIndex = 1;
                }

                Page.Title = Resources.GetResourceString("Profiles") + " > " + Resources.GetResourceString("I") + " | Microsoft Eneta";
            }
            else
            {
                companiesTitle.InnerText = Resources.GetResourceString("Companies");
                blogsTitle.InnerText = Resources.GetResourceString("Blogs");
                AnnouncementTitle.InnerText = Resources.GetResourceString("Announcements");
                editButton.Visible = false;

                if (CurrentUserIsAdmin)
                {
                    //AnnouncementView.ActiveViewIndex = 0;
                    AnnouncementView.ActiveViewIndex = 1;
                }
                else
                {
                    AnnouncementView.ActiveViewIndex = 1;
                }
            }

            if (SPContext.Current.Web.CurrentUser != null)
            {
                if (AddButtons != null)
                    AddButtons.Visible = true;
            }

            var msg = Request.QueryString["msg"] ?? string.Empty;
            if (!string.IsNullOrEmpty(msg))
                switch (msg.ToLower())
                {
                    case "compadd":
                        MessageLabel.Text = Resources.GetResourceString("CompanyAddedMessage");
                        break;
                    case "compsave":
                        MessageLabel.Text = Resources.GetResourceString("CompanySavedMesssage");
                        break;
                    case "blogadd":
                        MessageLabel.Text = Resources.GetResourceString("BlogAddedMessage");
                        break;
                    case "blogsave":
                        MessageLabel.Text = Resources.GetResourceString("BlogSavedMessage");
                        break;
                    case "annsave":
                        MessageLabel.Text = Resources.GetResourceString("AnnouncementAddedMessage");
                        break;
                    case "annedit":
                        MessageLabel.Text = Resources.GetResourceString("AnnouncementSavedMessage");
                        break;
                    case "booksave":
                        MessageLabel.Text = Resources.GetResourceString("BookAddedMessage");
                        break;
                    case "bookedit":
                        MessageLabel.Text = Resources.GetResourceString("BookSavedMessage");
                        break;
                    case "magazinesave":
                        MessageLabel.Text = Resources.GetResourceString("MagazineAddedMessage");
                        break;
                    case "magazineedit":
                        MessageLabel.Text = Resources.GetResourceString("MagazineSavedMessage");
                        break;
                    case "evtedit":
                    case "evtsave":
                        MessageLabel.Text = Resources.GetResourceString("EventSavedMessage");
                        break;
                    case "saved":
                        MessageLabel.Text = Resources.GetResourceString("ProfileSavedMessage");
                        break;
                }

            int id;
            int.TryParse(Request.QueryString["profileID"] ?? string.Empty, out id);
            var itemLocal = Item;
            if (itemLocal == null)
            {
                Response.Redirect(SPContext.Current.Site.Url);
                return;
            }

            if (!MyProfile)
                Page.Title = Resources.GetResourceString("Profiles") + " > " + itemLocal.Title + " | Microsoft Eneta";

            youTitle.InnerText = itemLocal.Title;
            _profileOwnerName = itemLocal.LiveIdToken; // itemLocal["SysID"].ToString();
            titleLabel.Text = itemLocal.UserName;
            headerUserNameLabel.Text = itemLocal.Title;

            titleImage.ImageUrl = itemLocal.UserImage32x32Url;  //"/_layouts/enetahandlers/userimagehandler.ashx?size=32&id=" + itemLocal.Id;
            profileLastChanged.Text = itemLocal.Modified.ToShortDateString(); // ((DateTime)itemLocal["Modified"]).ToShortDateString();

            firstNameContainer.Visible = itemLocal.ShowFirstName;
            if (firstNameContainer.Visible)
            {
                firstNameLabel.Text = itemLocal.FirstName;
                firstNameContainer.Visible = !string.IsNullOrEmpty(firstNameLabel.Text);
            }

            lastNameContainer.Visible = itemLocal.ShowLastName;
            if (lastNameContainer.Visible)
            {
                lastNameLabel.Text = itemLocal.LastName;
                lastNameContainer.Visible = !string.IsNullOrEmpty(lastNameLabel.Text);
            }

            emailContainer.Visible = itemLocal.ShowEmail;
            if (emailContainer.Visible)
            {
                emailAddressLink.NavigateUrl = "mailto:" + itemLocal.Email;
                emailAddressLink.Text = itemLocal.Email;
                emailContainer.Visible = !string.IsNullOrEmpty(emailAddressLink.Text);
            }

            var choiceValue = itemLocal.Interests;
            if (choiceValue.Count > 0)
            {
                var interests = string.Empty;

                for (var i = 0; i < choiceValue.Count; i++)
                    interests += ", " + choiceValue[i];
                interests = interests.Trim();
                if (interests.Length > 0)
                    interests = interests.Substring(1);

                interestsLabel.Text = interests;
            }
            interestsLabel.Visible = !string.IsNullOrEmpty(interestsLabel.Text);

            if (!string.IsNullOrEmpty(itemLocal.AboutMe))
            {
                aboutMeLabel.Text = itemLocal.AboutMe;
            }
            aboutMeContainer.Visible = !string.IsNullOrEmpty(aboutMeLabel.Text);

            if (!string.IsNullOrEmpty(itemLocal.Blog))
            {
                blogLink.NavigateUrl = itemLocal.Blog;
                blogLink.Text = itemLocal.Blog;
            }
            blogContainer.Visible = !string.IsNullOrEmpty(blogLink.NavigateUrl);


            addressContainer.Visible = itemLocal.ShowAddress;
            if (addressContainer.Visible)
            {
                addressLabel.Text = itemLocal.Address;
                addressContainer.Visible = !string.IsNullOrEmpty(addressLabel.Text);
            }

            phoneContainer.Visible = itemLocal.ShowPhone;
            if (phoneContainer.Visible)
            {
                phoneLabel.Text = itemLocal.Phone;
                phoneContainer.Visible = !string.IsNullOrEmpty(phoneLabel.Text);
            }

            contactsContainer.Visible = aboutMeContainer.Visible || blogContainer.Visible ||
                                        addressContainer.Visible || phoneContainer.Visible;

            schoolContainer.Visible = itemLocal.ShowSchool;
            if (schoolContainer.Visible)
            {
                schoolLabel.Text = itemLocal.School;
                schoolContainer.Visible = !string.IsNullOrEmpty(schoolLabel.Text);
            }

            fieldOfStudyContainer.Visible = itemLocal.ShowFieldOfStudy;
            if (fieldOfStudyContainer.Visible)
            {
                fieldOfStudyLabel.Text = itemLocal.FieldOfStudy;
                fieldOfStudyContainer.Visible = !string.IsNullOrEmpty(fieldOfStudyLabel.Text);
            }

            educationContainer.Visible = schoolContainer.Visible || fieldOfStudyContainer.Visible;

            companyContainer.Visible = itemLocal.ShowCompany;
            if (companyContainer.Visible)
            {
                companyLabel.Text = itemLocal.Company;
                companyContainer.Visible = !string.IsNullOrEmpty(companyLabel.Text);
            }


            jobTitleContainer.Visible = itemLocal.ShowJobTitle;
            if (jobTitleContainer.Visible)
            {
                jobTitleLabel.Text = itemLocal.JobTitle;
                jobTitleContainer.Visible = !string.IsNullOrEmpty(jobTitleLabel.Text);
            }

            jobContainer.Visible = companyContainer.Visible || jobTitleContainer.Visible;

            try
            {
                BindCompanies();
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            try
            {
                BindBlogs();
            }
            catch (Exception ex)
            {
                Logger.LogInfo("Application exception: ProfileControl.BindBlogs");
                Logger.LogException(ex);
            }
            try
            {
                BindAnnouncements();
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            try
            {
                BindEvents(itemLocal);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        private void BindEvents(UserProfileDto itemLocal)
        {
            try
            {
                int userId = 0;
                var siteId = SPContext.Current.Site.ID;

                SPSecurity.RunWithElevatedPrivileges(new SPSecurity.CodeToRunElevated(delegate
                {
                    using (var site = new SPSite(siteId))
                    using (var web = site.OpenWeb(GetWebUrl(site, EnetaApplication.PortalEventsSiteUrl)))
                    {
                        var user = web.SiteUsers[EnetaApplication.PortalUserNamePrefix + itemLocal.LiveIdToken];
                        userId = user.ID;
                    }
                }));

                var evtRepository = new EventRepository(EnetaApplication.PortalEventsSiteUrl);
                var userEvents = evtRepository.GetAllUserEvents(userId);
                if (userEvents.Count == 0)
                {
                    UserEventsList.Visible = false;
                }
                else
                {
                    if (MyProfile)
                        UserEventsList.Title = Resources.GetResourceString("MyEvents");
                    else
                        UserEventsList.Title = Resources.GetResourceString("Events");
                    UserEventsList.DataSource = userEvents;
                    UserEventsList.DataBind();
                }
            }
            catch (Exception ex)
            {
                UserEventsList.Visible = false;
                Logger.LogException(ex);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            MessageBox.Visible = !string.IsNullOrEmpty(MessageLabel.Text);
            MessageBox.Attributes["class"] = "slide-box success";

        }

        private void BindCompanies()
        {

            companiesTitle.Visible = false;
            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
            var onlyApproved = !MyProfile && !CurrentUserIsAdmin;

            var userName = EnetaApplication.PortalUserNamePrefix + _profileOwnerName;
            var companies = repository.GetUserCompanies(userName, onlyApproved);


            if (companies == null)
            {
                return;
            }

            if (companies.Count == 0)
            {
                return;
            }
            companiesTitle.Visible = true;
            companiesRepeater.DataSource = companies;
            companiesRepeater.DataBind();
        }

        private void BindBlogs()
        {
            blogsTitle.Visible = false;
            if (string.IsNullOrEmpty(_profileOwnerName))
            {
                Logger.LogInfo("BindBlogs(): _profileOwnerName is null or empty, returning");
                return;
            }

            var repository = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
            var userName = EnetaApplication.PortalUserNamePrefix + _profileOwnerName;
            var blogs = repository.GetUserBlogs(userName, MyProfile || CurrentUserIsAdmin);
            blogsRepeater.DataSource = blogs;
            blogsRepeater.DataBind();

            if (blogs != null)
                blogsTitle.Visible = (blogs.Count > 0);
        }

        private void BindAnnouncements()
        {
            try
            {
                var siteId = SPContext.Current.Site.ID;
                var sec = new SPSecurity.CodeToRunElevated(
                    delegate
                    {
                        using (var site = new SPSite(EnetaApplication.PortalAnnouncementsSiteUrl))
                        {
                            using (var web = site.OpenWeb(GetWebUrl(site, EnetaApplication.PortalAnnouncementsSiteUrl)))
                            {
                                var tmpWeb = site.OpenWeb();
                                var user = web.SiteUsers[EnetaApplication.PortalUserNamePrefix + _profileOwnerName];
                                var userId = user.ID;
                                tmpWeb.Dispose();
                                var listName = PublishingWeb.GetPagesListName(web);
                                var list = web.Lists[listName];

                                string queryString;
                                queryString =
                                    @"
                                        <Where>
                                            <And>
                                                <Or>
                                                    <Eq>
                                                        <FieldRef Name='Author' LookupId='True' />
                                                        <Value Type='User'>{0}</Value>
                                                    </Eq>
                                                    <Eq>
                                                        <FieldRef Name='RealAuthor' LookupId='True' />
                                                        <Value Type='User'>{1}</Value>
                                                    </Eq>
                                                </Or>
                                                <Eq>
                                                    <FieldRef Name='ContentType' />
                                                    <Value Type='Text'>{2}</Value>
                                                </Eq>
                                            </And>
                                        </Where>
                                        <OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>
                                    ";
                                queryString = string.Format(queryString,
                                                            userId, userId, ContentTypes.GetName(ContentTypes.Announcement));
                                Logger.LogWarning("BindAnnouncement: RealAuthor: " + userId);
                                //Response.Write(queryString);
                                var query = new SPQuery();
                                query.IncludeAllUserPermissions = false;
                                query.IncludePermissions = false;
                                query.Query = queryString;

                                var items = list.GetItems(query);
                                var itemsList = new List<SPListItem>();
                                foreach (SPListItem item in items)
                                {
                                    //if (item["ContentType"].ToString() != "Uudis")
                                    //    continue;
                                    if (MyProfile || CurrentUserIsAdmin)
                                        itemsList.Add(item);
                                    else if (
                                        item[
                                            item.Fields.
                                                GetFieldByInternalName(
                                                "_ModerationStatus").Id].
                                            ToString() == "0")
                                        itemsList.Add(item);
                                }

                                AnnouncementTitle.Visible = false;

                                if (itemsList.Count > 0)
                                    AnnouncementTitle.Visible = true;
                                if (itemsList.Count == 0)
                                {
                                    AnnouncementRepeater.Visible = false;
                                    AnnouncementUserRepeater.Visible = false;
                                    Logger.LogInfo("Teateid ei leitud");
                                }
                                if (CurrentUserIsAdmin)
                                {
                                    Logger.LogWarning("OnLoad(): Error databinding announcement view");
                                    AnnouncementUserRepeater.DataSource =
                                        itemsList;
                                    AnnouncementUserRepeater.DataBind();
                                }
                                else
                                {
                                    Logger.LogWarning("OnLoad(): Error databinding announcement view");
                                    AnnouncementUserRepeater.DataSource =
                                        itemsList;
                                    AnnouncementUserRepeater.DataBind();
                                }

                            }
                        }
                    });
                SPSecurity.RunWithElevatedPrivileges(sec);
            }
            catch (Exception ex)
            {
                Logger.LogWarning("OnLoad(): Error when loading announcements list");
                Logger.LogException(ex);
            }
        }

        private bool MyProfile
        {
            get
            {
                if (SPContext.Current.Web.CurrentUser == null)
                {
                    return false;
                }
                if (Item == null)
                {
                    Logger.LogInfo("MyProfile: Current item is null");
                    return false;
                }

                var userId = SPContext.Current.Web.CurrentUser.LoginName;
                var nameParts = userId.Split('|');
                userId = nameParts[nameParts.Length - 1];

                return (userId == Item.LiveIdToken);
            }
        }

        private bool CurrentUserIsAdmin
        {
            get
            {
                var user = SPContext.Current.Web.CurrentUser;
                if (user == null)
                    return false;

                return user.IsSiteAdmin;
            }
        }
        private string GetWebUrl(SPSite site, string webUrl)
        {
            webUrl = webUrl.Replace(site.Url, string.Empty);
            if (!webUrl.StartsWith("/"))
                webUrl = "/" + webUrl;
            return webUrl;
        }

    }
}
